package com.qf.ts.platform.front.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.qf.ts.platform.front.config.OssConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class AliyunOssUtil {

    @Autowired
    private OssConfig ossConfig;

    public String upload(File file) {
        if (file == null) {
            return null;
        }

        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String bucketName = ossConfig.getBucketName();

        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        //判断桶是否存在
        if (!client.doesBucketExist(bucketName)) {
            //当桶不存在时,则创建桶
            client.createBucket(bucketName);
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            //设置桶的权限为公共读
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            //发起创建桶的请求
            client.createBucket(createBucketRequest);
        }

        //images
        String fileHost = ossConfig.getFileHost();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String currentDate = format.format(new Date());

        //uuid产生的随机字符串中可能会带"-",
        // images/2020-11-14/dflafdajl-mv.jpg
        String baseUrl = fileHost + "/" + currentDate + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName();

        //真正的上传到oss服务器上的方法
        PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, baseUrl, file));
        client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

        if (result != null) {
            //上传成功后,返回该图片的存储地址
            return "/"+endpoint + baseUrl;
        }

        return null;
    }
}
